//
//  AlarmClockRemind.m
//  socket练习
//
//  Created by lianchuang on 14-11-11.
//  Copyright (c) 2014年 lianchuang. All rights reserved.
//

#import "AlarmClockRemind.h"

@implementation AlarmClockRemind



/**
 *  设置添加本地通知：用这个方法前 先要取消本地通知  用[[UIApplication sharedApplication] cancelAllLocalNotifications];然后重新设置
 *
 *  @param dateTime      时间
 *  @param isWorkingDays 是否工作日   YES 是工作日 NO 关闭工作日
 *
 *  @return 星期几个字符串 用空格分开
 */

-(NSString *)addLocalNotificationsWithTimes:(NSDate *)dateTime isWorkingDays:(BOOL)isWorkingDays category:(NSString *)category alertBody:(NSString *)alertBody Mark:(NSString *)mark{
    
    NSArray *arr = nil;
    if (isWorkingDays) {//是工作日
        arr = [[NSArray alloc]initWithObjects:[NSNumber numberWithInteger:WeekTypeOnMonday],
               [NSNumber numberWithInteger:WeekTypeOnTuesday],
               [NSNumber numberWithInteger:WeekTypeOnWednesday],
               [NSNumber numberWithInteger:WeekTypeOnThursday],
               [NSNumber numberWithInteger:WeekTypeOnFriday],nil];
    }else{
        arr = [[NSArray alloc]initWithObjects:[NSNumber numberWithInteger:WeekTypeOnMonday],
               [NSNumber numberWithInteger:WeekTypeOnTuesday],
               [NSNumber numberWithInteger:WeekTypeOnWednesday],
               [NSNumber numberWithInteger:WeekTypeOnThursday],
               [NSNumber numberWithInteger:WeekTypeOnFriday],
               [NSNumber numberWithInteger:WeekTypeOnSaturday],
               [NSNumber numberWithInteger:WeekTypeOnSunday], nil];
        
    }
    
    
    return [self setLocalNotificationsWithWeekTypes:arr Times:dateTime  category:category alertBody:alertBody Mark:mark];
}


/**
 *  设置添加本地通知：用这个方法前 先要取消本地通知  用[[UIApplication sharedApplication] cancelAllLocalNotifications];然后重新设置
 *
 *  @param weekTypes     星期的集合
 *  @param dateTime      时间  格式：10:10:00
 *
 *  @return 星期几个字符串 用空格分开
 */
-(NSString *)setLocalNotificationsWithWeekTypes:(NSArray *)weekTypes Times:(NSDate *)dateTime  category:(NSString *)category alertBody:(NSString *)alertBody Mark:(NSString *)mark{
    
    
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        
    //3.创建UIUserNotificationSettings，并设置消息的显示类类型
    UIUserNotificationSettings *uns = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:nil];
    
    //4.注册推送
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    [[UIApplication sharedApplication] registerUserNotificationSettings:uns];
    
    }

    
    
    
    
    NSMutableArray *weekStrArr = [[NSMutableArray alloc]initWithCapacity:10];
    NSArray *arrOneToFive = [[NSArray alloc]initWithArray:[self getWeekINDayWithWeekTypes:weekTypes]];
    
    
    MyNSLog("123====%@",[self getWeekINDayWithWeekTypes:weekTypes]);

    
    
    
    
    
    
    if (![weekTypes isEqual:[NSNull null]]||weekTypes !=nil||[weekTypes count]>0) {
        
        for (int i=0; i<arrOneToFive.count; i++) {
            
            NSString *timeStr = [AlarmClockRemind getTimeHHmmWithHHmmssDate:dateTime];
            
            

            UILocalNotification *notification = [[UILocalNotification alloc]init];
            notification.userInfo = [NSDictionary dictionaryWithObject:mark forKey:@"key"];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
//            [formatter setTimeZone:timeZone];
                [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
            notification.alertBody=alertBody;
            notification.repeatCalendar = [NSCalendar currentCalendar];
            //触发通知的时间
            NSDate *fromDate = [formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[arrOneToFive objectAtIndex:i],timeStr]];
//            NSDate *fromDate = [formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[arrOneToFive objectAtIndex:i],@"16:00:00"]];
            
            
//            NSTimeInterval fromDatef = [fromDate timeIntervalSince1970]+8*60*60;
//            
//           NSDate *fromDate1= [NSDate dateWithTimeIntervalSince1970:fromDatef];//经过时差处理的时间
            
  

            
            
            notification.fireDate=fromDate;
            
            //时区
            notification.timeZone = [NSTimeZone defaultTimeZone];
            //通知重复提示的单位，可以是天、周、月
            notification.repeatCalendar = [NSCalendar currentCalendar];
            notification.repeatInterval = NSWeekCalendarUnit;;
            //    notification.repeatInterval=kCFCalendarUnitWeek;
            notification.timeZone=[NSTimeZone defaultTimeZone];
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {

            notification.category = category;
            }
            notification.soundName=UILocalNotificationDefaultSoundName;
            
            [[UIApplication sharedApplication]  scheduleLocalNotification:notification];
            
            
            
            
            

            
            //  先定义一个遵循某个历法的日历对象
            NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
            //  通过已定义的日历对象，获取某个时间点的NSDateComponents表示，并设置需要表示哪些信息（NSYearCalendarUnit, NSMonthCalendarUnit, NSDayCalendarUnit等）
            
            
            NSDateComponents *dateComponents = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit fromDate:fromDate];
            
            
            MyNSLog("星期:%li", (long)dateComponents.weekday);
            
            [weekStrArr addObject:[NSString stringWithFormat:@"%ld",(long)dateComponents.weekday]];
            
        }
    }
    
    
    NSArray *sortArry =[[NSArray alloc]initWithArray:[AlarmClockRemind sorting:weekStrArr]];//排序后的数组
    
    
    NSMutableString *reTurnStrInts = [[NSMutableString alloc]initWithCapacity:10];//返回数据的数字字符串
    
    NSMutableString *reTurnStr = [[NSMutableString alloc]initWithCapacity:10];//中文字符串
    if (weekStrArr.count>0) {
        for (int i=0; i<sortArry.count; i++) {
            
            
            
            switch ([[sortArry objectAtIndex:i] integerValue]) {
                case 1:
                {
                    [reTurnStr appendString:@"星期日"];
                }
                    break;
                case 2:
                {
                    [reTurnStr appendString:@"星期一"];
                }
                    break;
                case 3:
                {
                    [reTurnStr appendString:@"星期二"];
                }
                    break;
                case 4:
                {
                    [reTurnStr appendString:@"星期三"];
                }
                    break;
                case 5:
                {
                    [reTurnStr appendString:@"星期四"];
                }
                    break;
                case 6:
                {
                    [reTurnStr appendString:@"星期五"];
                }
                    break;
                case 7:
                {
                    [reTurnStr appendString:@"星期六"];
                }
                    break;
                    
                default:
                    break;
            }
            
            if (sortArry.count-1==i) {
                
            }else{
                [reTurnStr appendString:@" "];
                
            }
            
            
            
            [reTurnStrInts appendString:[sortArry objectAtIndex:i]];
            
        }
        if ([reTurnStrInts isEqualToString:@"23456"]) {
            return @"工作日";
        }else if ([reTurnStrInts isEqualToString:@"71"]||[reTurnStrInts isEqualToString:@"17"]) {
            return @"周末";
        }
    }
    
    
    return reTurnStr;
}

/**
 *  计算当前日期内的的日期
 *
 *  @param weekTypes 存储存储周几的数组
 *
 *  @return 返回要设置日期（年月日 格式如：2014-11-10）数组
 */
-(NSArray *)getWeekINDayWithWeekTypes:(NSArray *)weekTypes{
    
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit|NSDayCalendarUnit
                                         fromDate:now];
    
    // 得到星期几
    // 1(星期天) 2(星期二) 3(星期三) 4(星期四) 5(星期五) 6(星期六) 7(星期天)
    NSInteger weekDay = [comp weekday];
    // 得到几号
    NSInteger day = [comp day];
    
    MyNSLog("weekDay:%ld   day:%ld",(long)weekDay,(long)day);
    
    // 计算当前日期和这周的星期一和星期天差的天数
    long firstDiff,lastDiff;
    if (weekDay == 1) {
        firstDiff = 1;
        lastDiff = 0;
    }else{
        firstDiff = [calendar firstWeekday] - weekDay;
        lastDiff = 9 - weekDay;
    }
    
    MyNSLog("firstDiff:%ld   lastDiff:%ld",firstDiff,lastDiff);
    
    // 在当前日期(去掉了时分秒)基础上加上差的天数
    NSDateComponents *firstDayComp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
    [firstDayComp setDay:day + firstDiff];
    NSDate *firstDayOfWeek= [calendar dateFromComponents:firstDayComp];
    
    NSDateComponents *lastDayComp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
    [lastDayComp setDay:day + lastDiff];
    NSDate *lastDayOfWeek= [calendar dateFromComponents:lastDayComp];
    
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy-MM-dd"];
    MyNSLog("星期日开始 %@",[formater stringFromDate:firstDayOfWeek]);
    
    
    long long int mondayInt = [firstDayOfWeek timeIntervalSince1970]+24*60*60*1;
    long long int  mtuesdayInt = [firstDayOfWeek timeIntervalSince1970]+24*60*60*2;
    long long int  wednesdayInt = [firstDayOfWeek timeIntervalSince1970]+24*60*60*3;
    long long int  thursdayInt = [firstDayOfWeek timeIntervalSince1970]+24*60*60*4;
    long long int  fridayInt = [firstDayOfWeek timeIntervalSince1970]+24*60*60*5;
    long long int  saturdayInt = [firstDayOfWeek timeIntervalSince1970]+24*60*60*6;
    
    
    [NSDate dateWithTimeIntervalSince1970:mondayInt];
    
    
    MyNSLog("星期一开始 %@",[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:mondayInt]]);
    MyNSLog("星期二开始 %@",[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:mtuesdayInt]]);
    MyNSLog("星期三开始 %@",[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:wednesdayInt]]);
    MyNSLog("星期四开始 %@",[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:thursdayInt]]);
    MyNSLog("星期五开始 %@",[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:fridayInt]]);
    MyNSLog("星期六开始 %@",[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:saturdayInt]]);
    
    
    NSMutableArray *arrayOneToFive = [[NSMutableArray alloc]initWithCapacity:10];
    
    if (![weekTypes isEqual:[NSNull null]]||weekTypes !=nil||[weekTypes count]>0) {
        for (int i=0; i<weekTypes.count; i++) {
            NSNumber *weekTypeNumber=(NSNumber*)[weekTypes objectAtIndex:i];
            WeekType weekType = [weekTypeNumber integerValue];
            
            
            
            switch (weekType) {
                case WeekTypeOnMonday:
                {
                    [arrayOneToFive addObject:[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:mondayInt]]];//添加周一
                    
                }
                    break;
                case WeekTypeOnTuesday:
                {
                    [arrayOneToFive addObject:[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:mtuesdayInt]]];//添加周二
                    
                }
                    break;
                case WeekTypeOnWednesday:
                {
                    [arrayOneToFive addObject:[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:wednesdayInt]]];//添加周三
                    
                }
                    break;
                case WeekTypeOnThursday:
                {
                    [arrayOneToFive addObject:[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:thursdayInt]]];//添加周四
                    
                }
                    break;
                case WeekTypeOnFriday:
                {
                    [arrayOneToFive addObject:[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:fridayInt]]];//添加周五
                    
                }
                    break;
                case WeekTypeOnSaturday:
                {
                    [arrayOneToFive addObject:[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:saturdayInt]]];//添加周六
                    
                }
                    break;
                case WeekTypeOnSunday:
                {
                    [arrayOneToFive addObject:[formater stringFromDate:firstDayOfWeek]];//添加周日
                    
                }
                    break;
                    
                default:
                    break;
            }
        }
    }
    /*
     
     
     [arrayOneToFive addObject:[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:mondayInt]]];//添加周一
     [arrayOneToFive addObject:[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:mtuesdayInt]]];//添加周二
     [arrayOneToFive addObject:[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:wednesdayInt]]];//添加周三
     [arrayOneToFive addObject:[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:thursdayInt]]];//添加周四
     [arrayOneToFive addObject:[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:fridayInt]]];//添加周五
     [arrayOneToFive addObject:[formater stringFromDate:[NSDate dateWithTimeIntervalSince1970:saturdayInt]]];//添加周六
     [arrayOneToFive addObject:[formater stringFromDate:firstDayOfWeek]];//添加周日
     
     
     
     NSLog(@"当前 %@",[formater stringFromDate:now]);
     NSLog(@"星期天结束 %@",[formater stringFromDate:lastDayOfWeek]);
     */
    return arrayOneToFive;
    
    
}
/**
 *  HH:mm 转换成HH:mm:ss 格式
 *
 *  @param timeStr HH:mm 格式字符串
 *
 *  @return HH:mm:ss 格式字符串
 */
+(NSString *)getTimeHHmmWithHHmmss:(NSString *)timeStr{
    NSString *dateStr=nil;
    if (timeStr !=nil||timeStr.length>0||![timeStr  isEqual:[NSNull null]]) {
        NSString *str = timeStr;
        
        NSDateFormatter *format=[[NSDateFormatter alloc]init];
        NSTimeZone* GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];
        [format setTimeZone:GTMzone];
        [format setDateFormat:@"HH:mm"];
        
        
        NSDate *stringD = [format dateFromString:[NSString stringWithFormat:@"%@",str]];
        
        NSDateFormatter *format1=[[NSDateFormatter alloc]init];
        NSTimeZone* GTMzone1 = [NSTimeZone timeZoneForSecondsFromGMT:0];
        [format1 setTimeZone:GTMzone1];
        [format1 setDateFormat:@"HH:mm:ss"];
        dateStr = [format1 stringFromDate:stringD];
        
    }
    return dateStr;
}

+(NSString *)getTimeHHmmWithHHmmssDate:(NSDate *)timeDate{
    NSString *dateStr=nil;
    if (timeDate !=nil||![timeDate  isEqual:[NSNull null]]) {
        
        NSDateFormatter *format=[[NSDateFormatter alloc]init];
        NSTimeZone* GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];
        [format setTimeZone:GTMzone];
        [format setDateFormat:@"HH:mm:ss"];

        dateStr = [format stringFromDate:timeDate];
        
    }
    return dateStr;
}

/**
 *  排序
 *
 *  @param sortArray 需要排序的数组
 *
 *  @return 返回排序后的数组
 */
+(NSArray *)sorting:(NSArray *)sortArray{
    //排序前
    NSMutableString *outputBefore = [[NSMutableString alloc] init];
    for(NSString *str in sortArray){
        [outputBefore appendFormat:@"%@",str];
    }
    MyNSLog("排序前:%@",outputBefore);
    
    NSArray *array = [sortArray sortedArrayUsingComparator:cmptr];
    NSMutableArray *outputAfterArr = [[NSMutableArray alloc]initWithCapacity:10];
    
    
    for(NSString *str in array){
        [outputAfterArr addObject:str];
    }
    MyNSLog("排序后:%@",outputAfterArr);
    return outputAfterArr;
}
NSComparator cmptr = ^(id obj1, id obj2){
    if ([obj1 integerValue] > [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }
    
    if ([obj1 integerValue] < [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
};


+(void)cancelLocalNotificationMark:(NSString *)mark{
    if (mark==nil||[mark isEqual:[NSNull null]]) {
        return;
    }
    UIApplication *app = [UIApplication sharedApplication];
    
    //获取本地推送数组
    
    NSArray *localArr = [app scheduledLocalNotifications];
    
    
    
    if (localArr) {
        
        for (UILocalNotification *noti in localArr) {
            
            NSDictionary *dict = noti.userInfo;
            
            if (dict) {
                
                NSString *inKey = [dict objectForKey:@"key"];
                
                if ([inKey isEqualToString:mark]) {
                    [app cancelLocalNotification:noti];
                }
                
            }
            
        }
        
        
    }

}

@end
